# -*-encoding: utf-8 -*-

from pyramid.view import view_config
from pyramid.view import view_defaults
from pyramid.response import Response
from pyramid.httpexceptions import HTTPFound
import json
from ..utils.Hash.HashUtil import HashUtil
from ..utils.Image.ImageUtil import ImageUtil
from ..utils.DB import MySqlCRUD
import time, os, uuid, shutil, hashlib
import base64
from ..utils.Queue import UploadTasks
from ..utils.SMS import MobSMS
from ..utils.Cache.TokenCache import TokenCache
from ..utils.Cache.ChecksumCache import ChecksumCache
import logging

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
log = logging.getLogger(__name__)

from WebBase import Base

class InfoEdit(Base):

    @view_config(route_name='AppWebPortraitEditRoute', request_method='POST')
    def AppWebPortraitEditRoute(self):
        try:
            postParams =  self.request.POST
            tel = self.request.session['tel']
            tString = self.request.session['tString']
            eString = self.request.session['eString']
            tokenString = self.request.session['tokenString']
            log.debug(postParams)
            uploadFile = postParams.getone('fileInput')
            input_file = uploadFile.file
            fileType = uploadFile.type
            if fileType == "image/jpeg":
                suffix = 'jpg'
            elif fileType == "image/bmp":
                suffix = 'bmp'
            elif fileType == "image/gif":
                suffix = 'gif'
            elif fileType == "image/png":
                suffix = 'png'
            elif fileType == "image/tiff":
                suffix = 'tiff'
            else:
                suffix = 'ERRORTYPE'
        except Exception, e:
            log.error(e)

        tmpTokenString = self.calculateToken(tString, tel)

        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            map = {'RetCode': '126', 'message': '流程验证失败!', 'data': '请重新登录'}
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        # The file instance
        fileMD5 = HashUtil.getFileMD5(input_file.read())
        fileName = fileMD5 + '.' + suffix
        log.debug('[PORTRAIT][MD5]' + fileMD5)

        # The file path
        file_path = os.path.join('/media/img', suffix, fileMD5[0: 2], fileMD5[2: 4], fileName)
        if os.path.isfile(file_path):
            pass
        else:
            temp_file_path = file_path + '.tmp'
            input_file.seek(0)
            folderName = file_path[0: file_path.rfind('/') + 1]
            if not os.path.exists(folderName):
                os.makedirs(folderName)

            with open(temp_file_path, 'wb') as output_file:
                shutil.copyfileobj(input_file, output_file)
            os.rename(temp_file_path, file_path)

        updateSQL = '''
            UPDATE user_info SET portrait = %s
                WHERE user_info.tel = %s;
                '''
        resultUpdate = MySqlCRUD.updateImpl(updateSQL, file_path, tel)
        map = {'RetCode': '0', 'message': '更新头像成功!', 'data': file_path}
        jsonStr = json.dumps(map, ensure_ascii=False)
        jsonStr = jsonStr.replace('/media', '/static')
        log.debug(jsonStr)
        #return Response(jsonStr)
        return HTTPFound('/AppWebIndex')

